/**
 * Created by 功振 on 2016/2/2.
 */

angular.module('NatureCloud').controller('BuildInfosControler',
    function ($scope,$rootScope,$uibModal, $state,$stateParams,isold, $log, $window, $cookies, buildListQuery, buildStart, buildStop, buildDelete, getWebhook,$mdDialog,updateWebhook,utilService,buildAddition,buildUpdate,$filter,$sce) {
        //var username = "kidqhj";
        var username = $cookies.get("username");
        $scope.repo_namespaces_loading = true;
        $scope.idTagMap = {};
        $scope.customFullscreen = false;
        $scope.build = {};
        $scope.buildInfos = $scope.buildInfos || [];
        $scope.buildnameReg = '[a-z0-9]+(?:[._-][a-z0-9]+)*';

        /**
         * 创建构建 侧滑
         * */
        $scope.pageSildeChecked=false;
        $scope.maskSelect=false;

        var operationType;
        //$scope.buildId = undefined;
        buildListQuery(username).then(function (r) {

            $scope.buildInfos = r.data.retlst;
            $scope.repo_namespaces_loading = false;
        }, function (r) {
            // alert fail
            alertify.error(r.data + "buildList query failed");
            // console.log(r.data + "buildList query failed");
        });

        if($stateParams.createRepoInfo !== undefined && $stateParams.createRepoInfo !== null){
            createSilder();

            $scope.build = $stateParams.createRepoInfo;
            $scope.build.gitPath = $stateParams.createRepoInfo.git_url;
            $scope.autoGet = $stateParams.createRepoInfo.autoGet;

        }

        $scope.currentPageBuilds = [];
        $scope.currentPage = 1;
        $scope.numPerPage = 10;
        $scope._curBuildInfo={};
      $scope.searchText="";

      $scope.$watch("buildInfos + currentPage", function() {
            var page=$scope.currentPage;
            if ($scope.buildInfos) {
                var begin = ((page - 1) * $scope.numPerPage)
                    , end = begin + $scope.numPerPage;
                $scope._curBuildInfo = $scope.buildInfos.slice(begin, end);
                $scope._curBuildInfo.forEach(function(buildInfo) {
                    //init
                    buildInfo.icon = "fa fa-"+buildInfo.type;
                    if(buildInfo.type === 'svn'){
                        buildInfo.iconName = 'svn';
                        buildInfo.icon='iconfont icon-svn';
                        buildInfo.color='#49cb6f'
                    }else if(buildInfo.type=== 'git'){
                        buildInfo.color='#01cad7'
                    }else{
                        buildInfo.color='#ef6293'
                    }
                });

                if($scope.searchText == ""){
                  $scope.currentPageBuilds = $scope._curBuildInfo;
                }else{
                  $scope.currentPageBuilds = $filter('filter')($scope.buildInfos, {'id': $scope.searchText})
                  $scope.currentPageBuilds.forEach(function(buildInfo) {
                    //init
                    buildInfo.icon = "fa fa-"+buildInfo.type;
                    if(buildInfo.type === 'svn'){
                      buildInfo.iconName = 'svn';
                      buildInfo.icon='iconfont icon-svn';
                      buildInfo.color='#49cb6f'
                    }else if(buildInfo.type=== 'git'){
                      buildInfo.color='#01cad7'
                    }else{
                      buildInfo.color='#ef6293'
                    }
                  });
                }
                $scope.searchTest="";
                _getTagModal();
            }
        });
      $scope.searchClick=function () {
        if ($scope.searchText == "") {
          $scope.searchPageHide=false;

          $scope.currentPageBuilds = $scope._curBuildInfo;
        } else {

          $scope.searchPageHide=true;
          $scope.currentPageBuilds = $filter('filter')($scope.buildInfos, {'id': $scope.searchText})
          $scope.currentPageBuilds.forEach(function(buildInfo) {
            //init
            buildInfo.icon = "fa fa-"+buildInfo.type;
            if(buildInfo.type === 'svn'){
              buildInfo.iconName = 'svn';
              buildInfo.icon='iconfont icon-svn';
              buildInfo.color='#49cb6f'
            }else if(buildInfo.type=== 'git'){
              buildInfo.color='#01cad7'
            }else{
              buildInfo.color='#ef6293'
            }
          });

        }

        }




        $scope.createBuilAuto = function (ev) {
            // $state.go("cp.repolist");
            operationType = 'creat';

          $mdDialog.show({
              controller:'BuildRepoLstController',
              templateUrl: 'createBuild.html',
              parent: angular.element(document.body),
              targetEvent: ev,
              clickOutsideToClose: true,
              fullscreen: true
          }).then(function (info) {
              if (info) {
                  // console.log(info);
                  $scope.build = info.item;
                  $scope.build.gitPath = info.item.clone_url;
                  $scope.autoGet = true;
              }
          }, function (r) {
              // alertify.error(r);
          });

        };



        $scope.buildHistory = function (id) {
            $state.go('cp.buildhistory',{
                runID:id
            });
        };


      $scope.gitPathBlur=function () {
            if($scope.build.gitPath==""){
              $scope.gitPathFlag=true;
              return;
            }else{
              $scope.gitPathFlag=false;
            }
          if($scope.build.gitPath.indexOf("github.com")>=0||$scope.build.gitPath.indexOf("bitbucket.org")>=0){
              $scope.codeTypeFlag=false;
            // console.log($scope.codeTypeFlag)
          }else{
            $scope.codeTypeFlag=true;
          }
        };

        $scope.confirmOperation = function () {
            if (operationType === 'creat'){
                $scope.build.buildContext = ($scope.build.buildContext === undefined) ? '' : $scope.build.buildContext;
                $scope.build.isCI = $scope.build.isCI === undefined ? false : $scope.build.isCI;
                $scope.build.user = username;
                buildAddition(angular.toJson($scope.build, true)).then(function (res) {
                    $scope.pageSildeChecked = false;
                    $scope.maskSelect = false;
                    $scope.buildInfos = $scope.buildInfos||[];
                    $scope.buildInfos.push($scope.build);
                },function (err) {
                    alertify.error('构建创建失败');
                });
            }else if (operationType === 'update'){
                $scope.build.user = username;
                buildUpdate(angular.toJson($scope.build, true)).then(function (r) {
                    var data = r.data.data;
                    if(data.n === 1 && data.nModified === 1 && data.ok === 1){
                        alertify.success("build update succeed");
                        // $scope.$watchCollection('buildInfos', function () {
                            for (var i = 0; i < $scope.buildInfos.length; i++) {
                                if ($scope.buildInfos[i].id == $scope.build.id) {
                                    $scope.buildInfos[i].icon = "fa fa-"+$scope.buildInfos[i].type;
                                    if($scope.buildInfos[i].type === 'svn'){
                                        $scope.buildInfos[i].iconName = 'svn';
                                        $scope.buildInfos[i].icon='iconfont icon-svn';
                                        $scope.buildInfos[i].color='#49cb6f'
                                    }else if($scope.buildInfos[i].type=== 'git'){
                                        $scope.buildInfos[i].color='#01cad7'
                                    }else{
                                        $scope.buildInfos[i].color='#ef6293'
                                    }
                                    $scope.buildInfos[i] = $scope.build;
                                }
                            }
                        // });

                        // for(var i = 0; i < $scope.buildInfos.length; i++){
                        //     var infos = $scope.buildInfos[i];
                        //     if(infos.id = $scope.build.id){
                        //         $scope.buildInfos[i] = $scope.build;
                        //     }
                        // }
                    }else{
                        alertify.error("数据库更新失败");
                    }
                    // alertify.success("build update succeed");
                    $scope.pageSildeChecked = false;
                    $scope.maskSelect = false;
                }, function (r) {
                    alertify.error("build update failed");
                });
            }

        };

        $scope.cancelCreat = function () {
            $scope.pageSildeChecked = false;
            $scope.maskSelect = false;
        };
        
        $scope.createDocker =function($event,buildInfo){
            $event.stopPropagation();
            var parm = buildInfo.params;
            isold(buildInfo.id).then(function (res) {
                var isOld = !res.ret;
           // var num = 0;
            // if(parm && parm !== '' && parm !== null){
            //     for(var i = 0; i < parm.length; i++){
            //         if(parm[i] === 'status'){
            //             num ++;
            //         }
            //     }
            //     if(num === 0){
            //         isOld = true;
            //     }
            // }

            if(isOld === true){
                // $mdDialog.show(
                //     $mdDialog.alert()
                //         .clickOutsideToClose(true)
                //         .title('Sorry')
                //         .textContent('您的构建版本过低，如想使用此功能，请重新创建构建')
                //         // .ariaLabel('svn')
                //         .ok('确定')
                // );
                $mdDialog.show({
                    controller: function ($scope,$cookies,updateWebhook,$mdDialog,params) {
                        $scope.dialogContent = params.content;
                        $scope.cancel = function () {
                            $mdDialog.cancel();
                        };

                    },
                    templateUrl: 'webhookWhetherSorry.html',
                    parent: angular.element(document.body),
                    // targetEvent: e,
                    clickOutsideToClose: true,
                    locals:{
                        params:{
                            content:"您的构建版本过低，尚不支持此功能，请重新创建后重试"
                        }
                    },
                    fullscreen:true
                });
            }else{
                var id=buildInfo.id;
                var codeRepoURL=buildInfo.gitPath;
                var type=buildInfo.type;
                var dockeradd=buildInfo.buildContext;
                var full_name=buildInfo.full_name;
                $cookies.put('getTag',id);

                $mdDialog.show({
                    controller: 'createDockerController',
                    templateUrl: 'template/cp/createDockerfile.html',
                    targetEvent: $event,
                    parent: angular.element(document.body),
                    locals: {
                        params: {
                            id: id,
                            codeRepoURL: codeRepoURL,
                            type: type,
                            full_name: full_name,
                            dockeradd:dockeradd,
                            idTagMap:$scope.idTagMap,
                            isOld:isOld,
                            branchtype:'branch'
                        }
                    },
                    fullscreen:true // Only for -xs, -sm breakpoints.
                });
            }

        })};

        $scope.testDocker =function($event,buildInfo){
            $event.stopPropagation();
            var parm = buildInfo.params;
            isold(buildInfo.id).then(function (res) {
                var isOld = !res.ret
                //var num = 0;
                // if(parm && parm !== '' && parm !== null){
                //     for(var i = 0; i < parm.length; i++){
                //         if(parm[i] === 'status'){
                //             num ++;
                //         }
                //     }
                //     if(num === 0){
                //         isOld = true;
                //     }
                // }
                if (isOld === true) {

                    $mdDialog.show({
                        controller: function ($scope,$cookies,updateWebhook,$mdDialog,params) {
                            $scope.dialogContent = params.content;
                            $scope.cancel = function () {
                                $mdDialog.cancel();
                            };

                        },
                        templateUrl: 'webhookWhetherSorry.html',
                        parent: angular.element(document.body),
                        // targetEvent: e,
                        clickOutsideToClose: true,
                        locals:{
                            params:{
                                content:"您的构建版本过低，尚不支持此功能，请重新创建后重试"
                            }
                        },
                        fullscreen:true
                    });

                    // $mdDialog.show(
                    //     $mdDialog.alert()
                    //         .clickOutsideToClose(true)
                    //         .title('Sorry')
                    //         .textContent('您的构建版本过低，如想使用此功能，请重新创建构建')
                    //         // .ariaLabel('svn')
                    //         .ok('确定')
                    // );
                } else {
                    var id = buildInfo.id;
                    var codeRepoURL = buildInfo.gitPath;
                    var type = buildInfo.type;
                    var dockeradd = buildInfo.buildContext;
                    var full_name = buildInfo.full_name;
                    $cookies.put('getTag', id);

                    $mdDialog.show({
                        controller: 'testDockerController',
                        templateUrl: 'template/cp/testDockerfile.html',
                        targetEvent: $event,
                        parent: angular.element(document.body),
                        locals: {
                            params: {
                                id: id,
                                codeRepoURL: codeRepoURL,
                                type: type,
                                full_name: full_name,
                                dockeradd: dockeradd,
                                idTagMap: $scope.idTagMap,
                                isOld: isOld
                            }
                        },
                        fullscreen: true // Only for -xs, -sm breakpoints.
                    });
                }
            })
        };


        $scope.startBuild = function (e,buildInfo) {
            e.stopPropagation();
            var parm = buildInfo.params;
            var num = 0;
            isold(buildInfo.id).then(function (res) {
                var isOld = !res.ret;
                if(parm && parm !== '' && parm !== null){
                    for(var i = 0; i < parm.length; i++){
                        if(parm[i] === 'status'){
                            num ++;
                        }
                    }
                    if(num <= 0){
                        isOld = true;
                    }else {
                        isOld = false;
                    }
                }
                var id = buildInfo.id;
                var codeRepoURL = buildInfo.gitPath;
                var type = buildInfo.type;
                var full_name = buildInfo.full_name;
                $cookies.put('getTag', id);
                _openModal(id, codeRepoURL, type, full_name, isOld);

            })
        };

        $scope.stop = function (id) {
            var username = $cookies.get("username");
            buildStop(username, id).then(function (r) {
                // alert success
                alertify.success(r + "build stop succeeded");
            }, function (r) {
                // alert fail
                alertify.error(r + "build stop failed");
            });
        };

        $scope.delete = function (e,buildInfo) {
            e.stopPropagation();
            var deleteInfo = {
                //user: username,
                id: buildInfo.id
            };
            $mdDialog.show({
                controller: function ($scope, $state, $mdDialog,params) {
                    $scope.bName=params.deleteInfo.id;
                    $scope.ok=function () {
                        buildDelete(params.deleteInfo).then(function (r) {
                            // alert success

                            /*if (r.ret == true) {
                                var _idx = params.buildInfos.indexOf(params.buildInfo);
                                params.buildInfos.splice(_idx, 1);
                                alertify.success($scope.bName + " build delete succeeded");
                            }*/
                            // $scope.$watchCollection('buildInfos', function () {
                            //     for (var i = 0; i < $scope.buildInfos.length; i++) {
                            //         if ($scope.buildInfos[i].id == jobID) {
                            //             $scope.buildInfos.splice(i, 1);
                            //         }
                            //     }
                            // });
                          $mdDialog.hide(r);

                        }, function (err) {
                          $mdDialog.cancel(err);

                          // alert fail
                            // alertify.error(r + "build delete failed");
                        });
                    }
                    $scope.cancel=function () {
                        $mdDialog.cancel();
                    }
                },
                templateUrl: 'storageDel.html',
                parent: angular.element(document.body),
                targetEvent: e,
                clickOutsideToClose: true,
                fullscreen: true,// Only for -xs, -sm breakpoints.
                locals: {
                    params: {
                        deleteInfo: deleteInfo,
                        buildInfo:buildInfo,
                        buildInfos:$scope.buildInfos
                    }
                }
            }).then(function (r) {
              if (r.ret == true) {
                var _idx = $scope.buildInfos.indexOf(buildInfo);
                $scope.buildInfos.splice(_idx, 1);
                alertify.success($scope.bName + " build delete succeeded");
              }
            },function(err){
              if(err)
                alertify.error(r + "build delete failed");
              // alertify.error('delete image ['+_name+']:['+_ver+'] error:'+err.data.data);
            })
        };

        $scope.update = function (e,buildInfo) {
            e.stopPropagation();
            operationType = 'update';

            isold(buildInfo.id).then(function (res) {
                var isOld = !res.ret;
                if (isOld === true){
                    $mdDialog.show({
                        controller: function ($scope,$cookies,updateWebhook,$mdDialog,params) {
                            $scope.dialogContent = params.content;
                            $scope.cancel = function () {
                                $mdDialog.cancel();
                            };

                        },
                        templateUrl: 'webhookWhetherSorry.html',
                        parent: angular.element(document.body),
                        // targetEvent: e,
                        clickOutsideToClose: true,
                        locals:{
                            params:{
                                content:"您的构建版本过低，尚不支持此功能，请重新创建后重试"
                            }
                        },
                        fullscreen:true
                    });
                }else{
                    $scope.pageSildeChecked=!$scope.pageSildeChecked;
                    $scope.maskSelect=!$scope.maskSelect;
                    $scope.op = 'update';
                    $scope.build = buildInfo;
                    if($scope.build.type !== 'git' && $scope.build.type !== 'svn'){
                        $scope.autoGet = true;
                    }else{
                        $scope.autoGet = false;
                    }
                    $scope.build.isCI = ($scope.build.isCI === undefined) ? $scope.build.isCI === false : $scope.build.isCI === $scope.build.isCI;
                    getWebhook(username, buildInfo.id).then(function (r) {
                        // console.log(r);
                        var data = r.data;
                        $scope.build.username = data.username;
                        $scope.build.password = data.password;
                    },function (err) {
                        alert.error('get data error');
                    });
                }

            });
        };

        $scope.webhookWhetherOpen = function (e,jobID) {
            e.stopPropagation();
            var username = $cookies.get("username");

            getWebhook(username,jobID).then(function (res) {
                var doc = res.data;
                var path = doc.gitPath;
                if(res.ret === true){
                    if(path !== undefined && path !== '' && path !== null){
                            if(doc.isCI === true ){
                                if(isContains(path,'github.com') === true || isContains(path,'bitbucket.org') === true){
                                    $mdDialog.show({
                                        controller: 'GetWebhookURLController',
                                        templateUrl: 'webhookWhetherOpening.html',
                                        parent: angular.element(document.body),
                                        targetEvent: e,
                                        clickOutsideToClose: true,
                                        locals:{
                                            params:{
                                                btn:false,
                                                data:doc
                                            }
                                        },
                                        fullscreen:true
                                    });
                                }else{
                                    $mdDialog.show({
                                        controller: function ($scope,$cookies,$mdDialog,params) {
                                            $scope.dialogContent = params.content;
                                            $scope.cancel = function () {
                                                $mdDialog.cancel();
                                            };

                                        },
                                        templateUrl: 'webhookWhetherSorry.html',
                                        parent: angular.element(document.body),
                                        // targetEvent: e,
                                        clickOutsideToClose: true,
                                        locals:{
                                            params:{
                                                content:'对于此平台尚未开通持续集成功能，您可以尝试github/bitbucket来体验此功能'
                                            }
                                        },
                                        fullscreen:true
                                    });
                                }


                            }else{
                                if(isContains(path,'github.com') === true || isContains(path,'bitbucket.org') === true){
                                    $mdDialog.show({
                                        controller: function ($scope,$cookies,updateWebhook,params,$mdDialog) {
                                            var data = params.data;
                                            var username = $cookies.get('username');
                                            $scope.openCI = function () {
                                                updateWebhook(username,data.id).then(function (res) {
                                                    if(res.data.ok === 1 && res.data.nModified === 1 && res.data.n === 1){
                                                        $mdDialog.show({
                                                            controller: 'GetWebhookURLController',
                                                            templateUrl: 'webhookWhetherOpening.html',
                                                            parent: angular.element(document.body),
                                                            targetEvent: e,
                                                            clickOutsideToClose: true,
                                                            locals:{
                                                                params:{
                                                                    btn:true,
                                                                    data:data
                                                                }
                                                            },
                                                            fullscreen:true
                                                        });
                                                    }
                                                });
                                            };
                                            $scope.cancel = function () {
                                                $mdDialog.cancel();
                                            };

                                        },
                                        templateUrl: 'webhookWhetherOpen.html',
                                        parent: angular.element(document.body),
                                        targetEvent: e,
                                        clickOutsideToClose: true,
                                        locals:{
                                            params:{
                                                data:doc
                                            }
                                        },
                                        fullscreen:true
                                    });
                                }else{
                                    $mdDialog.show({
                                        controller: function ($scope,$cookies,$mdDialog,params) {
                                            $scope.dialogContent = params.content;
                                            $scope.cancel = function () {
                                                $mdDialog.cancel();
                                            };

                                        },
                                        templateUrl: 'webhookWhetherSorry.html',
                                        parent: angular.element(document.body),
                                        // targetEvent: e,
                                        clickOutsideToClose: true,
                                        locals:{
                                            params:{
                                                content:'对于此平台尚未开通持续集成功能，您可以尝试github/bitbucket来体验此功能'
                                            }
                                        },
                                        fullscreen:true
                                    });
                                }

                            }
                    }
                }else{
                    $mdDialog.show({
                        controller: function ($scope,$cookies,updateWebhook,$mdDialog,params) {
                            $scope.dialogContent = params.content;
                            $scope.cancel = function () {
                                $mdDialog.cancel();
                            };

                        },
                        templateUrl: 'webhookWhetherSorry.html',
                        parent: angular.element(document.body),
                        // targetEvent: e,
                        clickOutsideToClose: true,
                        locals:{
                            params:{
                                content:"您的构建版本过低，尚不支持此功能，请重新创建后重试(暂时只支持GitHub/bitbucket平台)"
                            }
                        },
                        fullscreen:true
                    });
                }

            },function (err) {
                //
            });

      };

        function isContains(str,substr) {
            return str.indexOf(substr) >= 0;
        }

        function _clearReqTagCookie(){
            $cookies.remove("getTag");
        }

        function _openModal(id, codeRepoURL, type, full_name, isOld){

            var modalInstance = $uibModal.open({
                animation: $scope.animationsEnabled,
                templateUrl: 'template/cp/buildStart.html',
                controller: 'BuildStartController',
                size: id,
                resolve: {
                    params: {
                        id: id,
                        codeRepoURL: codeRepoURL,
                        type: type,
                        full_name: full_name,
                        idTagMap:$scope.idTagMap,
                        isOld:isOld
                    }
                }
            });

            modalInstance.result.then(function (selectedItem) {
                $scope.selected = selectedItem;
                _clearReqTagCookie();
            }, function () {
                _clearReqTagCookie();
            });

        }

        function _getTagModal(){
            if ($scope.buildInfos && $stateParams.id !== undefined) {
                var _item = _getStateItem($stateParams.id);
                if(_item !== undefined){
                    _openModal(_item.id,_item.gitPath,_item.type,_item.full_name);
                }
            }
        }

        function _getStateItem(id){
            var _ret = undefined;
            $scope.buildInfos.forEach(function(one){
                if(one.id === id)
                    _ret = one;
            });
            return _ret;
        }

        $scope.buildSilder=function () {
            createSilder();
        };

        function createSilder(){
            operationType = 'creat';
            $scope.build = {};
            $scope.op = 'creat';
            $scope.pageSildeChecked=!$scope.pageSildeChecked;
            $scope.maskSelect=!$scope.maskSelect;
            $scope.autoGet = false;
            $scope.build.gitPath="";
            $scope.build.type="git";
          $scope.codeTypeFlag=false;
          $scope.gitPathFlag=false;
        }

});